package com.xw.comm.service.impl;

import com.xw.comm.service.PythonRunService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author ：xiongwei
 * @date ：Created in 2021/3/2 23:31
 */
@Slf4j
@Service
public class PythonRunServiceImpl implements PythonRunService {

    @Value("${command.python.exe.path}")
    private String path;

    @Override
    public void runWebTest() {
        runWebTest(true);
    }

    @Override
    public void runWebTest(boolean start) {
        runAbsolutelyCommand("D:\\ProgramData\\Anaconda3\\python.exe D:\\data\\python\\webTest\\httpTest.py");
    }

    @Override
    public void runAbsolutelyCommand(String command) {
        Process proc;
        try {
            // 执行py文件
            proc = Runtime.getRuntime().exec(command);
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                log.info("line = {}", line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void runPythonFile(String filePath) {
        if (filePath == null) {
            log.info("python路径为null");
            return;
        }
        String command = path + " " + filePath;
        runAbsolutelyCommand(command);
    }


    @Override
    public void runAsyncPythonFile(String filePath) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (filePath == null) {
            log.info("python路径为null");
            return;
        }
        log.info("runAsyncPythonFile = {}", filePath);
    }


}
